#!/usr/bin/env python3
"""
HR系统完备性测试 - 真实应用场景
模拟HR日常工作中的各种查询和操作需求
"""

import requests
import json
import time
import random
from datetime import datetime

class ComprehensiveHRTest:
    def __init__(self, base_url="http://localhost:8089"):
        self.base_url = base_url
        self.test_results = []
        
    def make_request(self, message, expected_features=None):
        """发送请求并检查响应"""
        try:
            print(f"\n💬 HR查询: {message}")
            
            response = requests.post(
                f"{self.base_url}/api/chat",
                json={"message": message},
                timeout=20
            )
            
            if response.status_code != 200:
                print(f"❌ HTTP错误: {response.status_code}")
                return False
                
            data = response.json()
            
            if not data.get('success'):
                print(f"❌ API错误: {data.get('error', 'Unknown')}")
                return False
            
            # 检查响应质量
            message_response = data.get('message', '')
            ui_commands = data.get('ui_commands', [])
            candidates = data.get('analyzed_candidates', [])
            
            print(f"✅ AI响应长度: {len(message_response)} 字符")
            print(f"✅ UI指令数量: {len(ui_commands)}")
            print(f"✅ 候选人数量: {len(candidates)}")
            
            if len(ui_commands) > 0:
                commands = [cmd.get('command') for cmd in ui_commands]
                print(f"✅ UI指令类型: {commands}")
            
            # 检查期望特性
            if expected_features:
                for feature, expected in expected_features.items():
                    if feature == "has_candidates" and expected:
                        if len(candidates) == 0:
                            print(f"⚠️  期望有候选人数据，但实际为空")
                    elif feature == "has_ui_commands" and expected:
                        if len(ui_commands) == 0:
                            print(f"⚠️  期望有UI指令，但实际为空")
                    elif feature == "min_response_length" and expected:
                        if len(message_response) < expected:
                            print(f"⚠️  响应长度不足：期望>{expected}，实际{len(message_response)}")
            
            return True
            
        except Exception as e:
            print(f"❌ 请求失败: {e}")
            return False

    def run_candidate_screening_tests(self):
        """候选人筛选场景测试"""
        print("\n🔍 === 候选人筛选场景测试 ===")
        
        tests = [
            {
                "message": "我需要找3个有Python经验的后端工程师，最好有2年以上工作经验",
                "expected": {"has_candidates": True, "has_ui_commands": True}
            },
            {
                "message": "筛选出所有会Java和Spring框架的候选人",
                "expected": {"has_candidates": True, "has_ui_commands": True}
            },
            {
                "message": "找一些前端开发者，要求掌握React和TypeScript",
                "expected": {"has_candidates": True, "has_ui_commands": True}
            },
            {
                "message": "有没有既会Python又会Go语言的全栈工程师？",
                "expected": {"has_candidates": True, "has_ui_commands": True}
            },
            {
                "message": "我要招聘团队领导，需要有管理经验的候选人",
                "expected": {"has_candidates": True, "has_ui_commands": True}
            }
        ]
        
        success_count = 0
        for i, test in enumerate(tests, 1):
            print(f"\n📋 筛选测试 {i}/5")
            if self.make_request(test["message"], test["expected"]):
                success_count += 1
            time.sleep(2)
        
        print(f"\n📊 筛选测试结果: {success_count}/{len(tests)} 通过")
        return success_count == len(tests)

    def run_interview_management_tests(self):
        """面试管理场景测试"""
        print("\n📝 === 面试管理场景测试 ===")
        
        tests = [
            {
                "message": "给候选人10751444出5道Python面试题，难度设为高级",
                "expected": {"has_ui_commands": True, "min_response_length": 100}
            },
            {
                "message": "为候选人12415691设计一套前端技术面试题",
                "expected": {"has_ui_commands": True, "min_response_length": 100}
            },
            {
                "message": "我需要为Go开发岗位准备面试题目，包含基础和进阶题",
                "expected": {"min_response_length": 200}
            },
            {
                "message": "候选人13879043已经通过了初试，请将其状态更新为待二面",
                "expected": {"has_ui_commands": True}
            },
            {
                "message": "分析一下候选人10751444的技能匹配度，他适合我们的Python工程师岗位吗？",
                "expected": {"min_response_length": 150}
            }
        ]
        
        success_count = 0
        for i, test in enumerate(tests, 1):
            print(f"\n📝 面试测试 {i}/5")
            if self.make_request(test["message"], test["expected"]):
                success_count += 1
            time.sleep(3)
        
        print(f"\n📊 面试测试结果: {success_count}/{len(tests)} 通过")
        return success_count == len(tests)

    def run_data_analysis_tests(self):
        """数据分析场景测试"""
        print("\n📈 === 数据分析场景测试 ===")
        
        tests = [
            {
                "message": "分析一下所有候选人的技能分布情况，哪些技能最热门？",
                "expected": {"min_response_length": 200}
            },
            {
                "message": "统计有多少候选人有Python经验，多少人有Java经验？",
                "expected": {"min_response_length": 100}
            },
            {
                "message": "按工作经验年限对候选人进行分组统计",
                "expected": {"min_response_length": 150}
            },
            {
                "message": "我们的候选人中，平均工作经验是多少年？",
                "expected": {"min_response_length": 50}
            },
            {
                "message": "生成一份候选人质量报告，包括技能匹配度分析",
                "expected": {"min_response_length": 300}
            }
        ]
        
        success_count = 0
        for i, test in enumerate(tests, 1):
            print(f"\n📈 分析测试 {i}/5")
            if self.make_request(test["message"], test["expected"]):
                success_count += 1
            time.sleep(2)
        
        print(f"\n📊 分析测试结果: {success_count}/{len(tests)} 通过")
        return success_count == len(tests)

    def run_batch_operations_tests(self):
        """批量操作场景测试"""
        print("\n🔄 === 批量操作场景测试 ===")
        
        tests = [
            {
                "message": "将所有Python技能超过8分的候选人标记为重点关注",
                "expected": {"min_response_length": 100}
            },
            {
                "message": "批量更新所有前端工程师候选人的状态为已联系",
                "expected": {"min_response_length": 100}
            },
            {
                "message": "找出所有工作经验少于1年的新人候选人，给他们发送培训信息",
                "expected": {"has_candidates": True}
            },
            {
                "message": "为所有Go语言开发者生成统一的技能评估报告",
                "expected": {"min_response_length": 200}
            }
        ]
        
        success_count = 0
        for i, test in enumerate(tests, 1):
            print(f"\n🔄 批量测试 {i}/4")
            if self.make_request(test["message"], test["expected"]):
                success_count += 1
            time.sleep(3)
        
        print(f"\n📊 批量测试结果: {success_count}/{len(tests)} 通过")
        return success_count == len(tests)

    def run_complex_query_tests(self):
        """复杂查询场景测试"""
        print("\n🎯 === 复杂查询场景测试 ===")
        
        tests = [
            {
                "message": "我需要找到既有Python又有Go经验，工作经验在3-5年之间，并且有团队管理经验的候选人",
                "expected": {"has_candidates": True, "has_ui_commands": True}
            },
            {
                "message": "对比候选人10751444和12415691的技能和经验，谁更适合我们的全栈工程师岗位？",
                "expected": {"min_response_length": 300}
            },
            {
                "message": "基于当前所有候选人的情况，推荐最适合担任技术负责人的3个人选",
                "expected": {"has_candidates": True, "min_response_length": 200}
            },
            {
                "message": "如果我要组建一个5人的开发团队（包含前端、后端、全栈），你会推荐哪些候选人？",
                "expected": {"has_candidates": True, "min_response_length": 300}
            }
        ]
        
        success_count = 0
        for i, test in enumerate(tests, 1):
            print(f"\n🎯 复杂测试 {i}/4")
            if self.make_request(test["message"], test["expected"]):
                success_count += 1
            time.sleep(4)
        
        print(f"\n📊 复杂测试结果: {success_count}/{len(tests)} 通过")
        return success_count == len(tests)

    def run_conversational_tests(self):
        """对话式查询测试"""
        print("\n💬 === 对话式查询测试 ===")
        
        tests = [
            {
                "message": "你好，我是新来的HR，能介绍一下系统的主要功能吗？",
                "expected": {"min_response_length": 200}
            },
            {
                "message": "我们公司的招聘标准和流程是什么？",
                "expected": {"min_response_length": 150}
            },
            {
                "message": "如何评估一个候选人的技术能力？",
                "expected": {"min_response_length": 200}
            },
            {
                "message": "面试过程中需要注意哪些问题？",
                "expected": {"min_response_length": 150}
            },
            {
                "message": "谢谢你的帮助，这个系统很有用！",
                "expected": {"min_response_length": 30}
            }
        ]
        
        success_count = 0
        for i, test in enumerate(tests, 1):
            print(f"\n💬 对话测试 {i}/5")
            if self.make_request(test["message"], test["expected"]):
                success_count += 1
            time.sleep(2)
        
        print(f"\n📊 对话测试结果: {success_count}/{len(tests)} 通过")
        return success_count == len(tests)

    def run_all_tests(self):
        """运行所有测试"""
        print("🚀 开始HR系统完备性测试")
        print("=" * 60)
        
        # 检查系统状态
        try:
            response = requests.get(f"{self.base_url}/api/status", timeout=5)
            if response.status_code == 200:
                data = response.json()
                print(f"📊 系统状态: {data['system_status']}")
                print(f"📊 候选人数量: {data['candidate_count']}")
                print(f"📊 系统版本: {data.get('version', 'Unknown')}")
            else:
                print("❌ 无法获取系统状态")
                return False
        except Exception as e:
            print(f"❌ 系统连接失败: {e}")
            return False
        
        # 运行各类测试
        test_results = []
        
        test_results.append(self.run_candidate_screening_tests())
        test_results.append(self.run_interview_management_tests()) 
        test_results.append(self.run_data_analysis_tests())
        test_results.append(self.run_batch_operations_tests())
        test_results.append(self.run_complex_query_tests())
        test_results.append(self.run_conversational_tests())
        
        # 生成总结报告
        passed_tests = sum(test_results)
        total_tests = len(test_results)
        
        print("\n" + "=" * 60)
        print("🎯 HR系统完备性测试总结")
        print("=" * 60)
        
        test_names = [
            "候选人筛选功能",
            "面试管理功能", 
            "数据分析功能",
            "批量操作功能",
            "复杂查询功能",
            "对话交互功能"
        ]
        
        for i, (name, result) in enumerate(zip(test_names, test_results)):
            status = "✅ 通过" if result else "❌ 失败"
            print(f"{i+1}. {name}: {status}")
        
        print(f"\n📊 整体通过率: {passed_tests}/{total_tests} ({passed_tests/total_tests*100:.1f}%)")
        
        if passed_tests == total_tests:
            print("🎉 恭喜！HR系统通过了完备性测试，可以满足实际HR工作需求！")
        elif passed_tests >= total_tests * 0.8:
            print("⚠️  系统基本可用，但还有改进空间")
        else:
            print("❌ 系统存在重要缺陷，需要进一步完善")
        
        return passed_tests >= total_tests * 0.8

if __name__ == "__main__":
    tester = ComprehensiveHRTest()
    success = tester.run_all_tests()
    exit(0 if success else 1)





